package us.wili.dev.common.util.sms.aliyun;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import us.wili.dev.common.util.sms.AliyunErrorCodeEnum;
import us.wili.dev.common.util.sms.AliyunSmsExpcetion;
import us.wili.dev.common.util.sms.alidayu.AlidayuProperties;

/**
 * Created by JasonY on 17/11/16.
 */
public class AliyunSmsUtil {

    private AliyunSmsProperties properties;

    public AliyunSmsUtil() {
    }

    public AliyunSmsUtil(AliyunSmsProperties properties) {
        this.properties = properties;
    }

    public void sendNormalSms(String phone, String templateCode, String content) {
        SendSmsResponse sendSmsResponse;

        IClientProfile profile = DefaultProfile.getProfile(properties.getRegionId(), properties.getAccessKeyId(),
                properties.getAccessKeySecret());
        try {
            DefaultProfile.addEndpoint(properties.getEndpointName(), properties.getRegionId(), properties.getProduct(), properties.getDomain());
            IAcsClient acsClient = new DefaultAcsClient(profile);

            SendSmsRequest request = new SendSmsRequest();
            request.setMethod(MethodType.POST);
            request.setPhoneNumbers(phone);
            request.setSignName(properties.getSignName());
            request.setTemplateCode(templateCode);
            request.setTemplateParam(content);
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            throw new AliyunSmsExpcetion(AliyunErrorCodeEnum.DEFAULT_EXCEPTION.getMsg());
        }
        if (sendSmsResponse.getCode() == null) {
            throw new AliyunSmsExpcetion(AliyunErrorCodeEnum.DEFAULT_EXCEPTION.getMsg());
        }
        if (sendSmsResponse.getCode() != null && !sendSmsResponse.getCode().equals("OK")) {
            AliyunErrorCodeEnum errorCodeEnum = AliyunErrorCodeEnum.get(sendSmsResponse.getCode());
            throw new AliyunSmsExpcetion(errorCodeEnum.getMsg());
        }
    }

    public void sendNormalSms(String phone, String content) {
        if (properties.getTemplateCode() == null) {
            throw new AliyunSmsExpcetion("templateCode can not bu null");
        }

        sendNormalSms(phone, properties.getTemplateCode(), content);
    }

    public AliyunSmsProperties getProperties() {
        return properties;
    }

    public void setProperties(AliyunSmsProperties properties) {
        this.properties = properties;
    }



}
